package com.yam.michael.hibernate.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.xunjia.exception.XunjiaException;
import com.yam.michael.hibernate.dao.AdvSerialDao;
import com.yam.michael.hibernate.pojo.AdvSerial;

public class AdvSerialDaoImpl extends HibernateDaoSupport implements AdvSerialDao ,Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6891466085417942984L;
	//日志
	private static final Logger logger = Logger.getLogger(AdvSerialDaoImpl.class);

	@Override
	/**
	 * 增加关键字广告系列
	 * @param advSerial
	 * @throws XunjiaException
	 */
	public Long addAdvSerial(AdvSerial advSerial) throws XunjiaException {
		try {
			return (Long)this.getHibernateTemplate().save(advSerial);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("添加广告系列发生错误,添加失败");
		}
	}

	@Override
	/**
	 * 删除关键字系列
	 * @param advSerial
	 * @throws XunjiaException
	 */
	public void deleteAdvSerial(AdvSerial advSerial) throws XunjiaException {
		try {
			this.getHibernateTemplate().delete(advSerial);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("删除广告系列发生错误,删除失败");
		}
	}
	@Override
	/**
	 * 更新关键字系列
	 * @param advSerial
	 * @throws XunjiaException
	 */
	public void updateAdvSerial(AdvSerial advSerial) throws XunjiaException {
		try {
			this.getHibernateTemplate().saveOrUpdate(advSerial);
		} catch (DataAccessException e) {
			logger.info(e.getMessage());
			throw new XunjiaException("更新广告系列发生错误,更新失败");
		}
	}
	/**
	 * 获取所有广告系列
	 * @return
	 * @throws XunjiaException
	 */
	@SuppressWarnings("unchecked")
	public List<AdvSerial> getAdvSerial(final String ownerUserId)throws XunjiaException{
		return (List<AdvSerial>) this.getHibernateTemplate().execute(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery("FROM AdvSerial AS a WHERE a.ownerUserId=?");
				q.setString(0, ownerUserId);
				return q.list();
			}});
	}
}
